<?php

/**
 * alltosun.com 商品控制器 index.php
 * ============================================================================
 * 版权所有 (C) 2009-2014 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址: http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明: 这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $Author: 吴松键 (wusj@alltosun.com) $
 * $Date: 2014-8-8 下午12:36:18 $
 * $Id$
 */
class Action
{
    private $per_page = 100;

    /**
     * 显示商品列表
     */
    public function index() {

        $page_no = $status = $stock = $is_sale = $category_id = $search_filter = $goods_snapshot_id = null;

        extract(URLTracker::init(array(
            'page_no' => 1,
            'status' => 1,
            'stock' => 1,
            'is_sale' => 1,
            'category_id' => 0,
            'search_filter' => array(),
            'goods_snapshot_id' => 0,
        )));

        // 拼装搜索条件
        $is_empty = 0;

        $filter = array();

        if (isset($search_filter['title']) && $search_filter['title']) {
            $filter['`title` LIKE '] = '%' . $search_filter['title'] . '%';
        }

        if ($category_id > 0) {
            $filter['category_id'] = $category_id;
        }

        if ((isset($search_filter['start_price']) && $search_filter['start_price']) ||
            (isset($search_filter['end_price']) && $search_filter['end_price'])
        ) {
            if ($start_price_res = goods_helper::get_goods_by_price($search_filter['start_price'], $search_filter['end_price'])) {
                $filter['id'] = $start_price_res;
            } else {
                $is_empty = 1;
            }
        }
        if (isset($search_filter['start_sale']) && $search_filter['start_sale']) {
            $filter['sale_count >='] = $search_filter['start_sale'];
        }
        if (isset($search_filter['end_sale']) && $search_filter['end_sale']) {
            $filter['sale_count <='] = $search_filter['end_sale'];
        }
        if (isset($search_filter['start_date']) && $search_filter['start_date']) {
            $filter['add_time >='] = $search_filter['start_date'] . ' 00:00:00';
        }
        if (isset($search_filter['end_date']) && $search_filter['end_date']) {
            $filter['add_time <='] = $search_filter['end_date'] . ' 23:59:59';
        }
        $filter['status'] = $status;
        $filter['is_sale'] = $is_sale;
        if ($stock == 1) {
            $filter['id'] = goods_helper::get_goods_ids_by_stock();
        } elseif ($stock == 2) {
            if (goods_helper::get_goods_ids_by_stock()) {
                $filter['`id` NOT'] = goods_helper::get_goods_ids_by_stock();
            }
        }
        if (isset($goods_snapshot_id) && $goods_snapshot_id) {
            $filter['id'] = _uri('goods_snapshot', $goods_snapshot_id, 'goods_id');
        }


        $category_list = goods_config::goods_category();

        $goods_list = array();
        if (!$is_empty) {
            $goods_count = _model('goods')->getTotal($filter);
            if ($goods_count) {
                $pager = new Pager($this->per_page);
                if ($pager->generate($goods_count)) {
                    Response::assign('pager', $pager);
                }

                $goods_list = _model('goods')->getList($filter, ' ORDER BY `view_order` DESC, `id` DESC ' .
                                                                $pager->getLimit($page_no));

                // 哪个SB写的???
                // 取实际SKU信息
                foreach ($goods_list as $key => $value) {

                    $sku_info = goods_helper::get_sku_info_by_goods_id($value['id']);

                    if (!empty($sku_info)) {
                        // 获取商品价格
                        $goods_list[$key]['price'] = $sku_info['price'];
                        // 获取商品价格差价
                        $goods_list[$key]['diff_price'] = $sku_info['diff_price'];
                        // 获取商品库存
                        $goods_list[$key]['stock'] = $sku_info['stock'];
                        // 商品抱抱币
                        $goods_list[$key]['bbcoin'] = intval($sku_info['bbcoin']);
                        // 商品抱抱币
                        $goods_list[$key]['diff_bbcoin'] = intval($sku_info['diff_bbcoin']);
                        // 分类名称
                        $goods_list[$key]['category_name'] = $category_list[$value['category_id']]['title'];
                    }
                }
            }
        }


        // 获取渠道列表
        $channel_list = channel_helper::get_channel_list();
        Response::assign('channel_list', $channel_list);

        Response::assign('goods_list', $goods_list);
        Response::assign('status', $status);

        Response::assign('stock', $stock);
        Response::assign('is_sale', $is_sale);

        Response::assign('category_list', $category_list);
        Response::assign('search_filter', $search_filter);
        Response::display('admin/goods_list.html');
    }

    /**
     * 选择商品分类
     */
    public function select_category() {
        $category_id = Request::getParam('category_id', 0);
        $id = Request::getParam('id', 0);

        $category_info = _uri('category', $category_id);

        Response::assign('category_info', $category_info);
        Response::assign('id', $id);
        Response::assign('category_id', $category_id);

        Response::display('admin/select_category.html');
    }

    public function get_sku_list() {
        $goods_id = Request::Post('id', 0);

        $goods_info = _uri('goods', $goods_id);

        if (!$goods_info) {
            return '请选择要查看的商品';
        }

        $sku_ids = _model('sku_relation')->getFields('sku_id', array('goods_id' => $goods_id), ' ORDER BY `property_id` ASC , `property_value_id` ASC, `sku_id` ASC ');
        $sku_ids = array_unique($sku_ids);
        $sku_list = array();
        if (!empty($sku_ids[0])) {
            foreach ($sku_ids as $k => $v) {
                $sku_info = _uri('sku', array('id' => $v));
                $line_list = goods_helper::get_property_value_by_sku_id($v);

                $sku_value_ids = '';
                foreach ($line_list as $key => $value) {
                    foreach ($value['value_list'] as $pkey => $pval) {
                        $sku_value_ids .= '-' . $pval['property_value_id'];
                    }
                }

                $sku_info['line_list'] = $line_list;
                $sku_info['sku_value_ids'] = trim($sku_value_ids, '-');
                $sku_list[] = $sku_info;
            }
        }
        Response::assign('sku_list', $sku_list);
        Response::assign('goods_info', $goods_info);
        Response::display('admin/sku_info.html');
    }

    public function get_gift_list() {
        $goods_id = Request::Post('id', 0);

        $goods_info = _uri('goods', $goods_id);

        if (!$goods_info) {
            return '请选择要添加赠品的商品';
        }

        $list = array();

        $list = _model('goods_gift_relation')->getList(array('goods_id' => $goods_id));

        foreach ($list as $k => $v) {
            $goods_title = _uri('goods', $v['gift_id'], 'title');
            $sku_info = goods_helper::get_sku_property($v['gift_sku_id']);
            $list[$k]['sku_info'] = $goods_title . ' ' . $sku_info;
        }

        return $list;
    }

    public function gift_edit() {
        $num = Request::Post('num', 0);
        $gift_id = Request::Post('gift_id', 0);

        if (!$num) {
            return '请填写要赠送的数量';
        }

        $gift_info = _uri('goods_gift_relation', $gift_id);

        if (!$gift_info) {
            return '该赠送商品不存在';
        }

        _model('goods_gift_relation')->update($gift_id, array('gift_num' => $num));

        return 'ok';
    }

    public function gift_del() {
        $gift_id = Request::Post('gift_id', 0);

        $gift_info = _uri('goods_gift_relation', $gift_id);

        if (!$gift_info) {
            return '该赠送商品不存在';
        }

        _model('goods_gift_relation')->delete($gift_id);

        return 'ok';
    }

    public function get_add_gift_list() {
        $goods_id = Request::Post('goods_id', 0);

        $goods_info = _uri('goods', $goods_id);

        if (!$goods_info) {
            return '该商品不存在';
        }

        $list = array();

        $goods_ids = _model('goods')->getFields('id', array('status' => 1));
        $list = _model('sku')->getList(array('goods_id' => $goods_ids));

        foreach ($list as $k => $v) {
            $goods_title = _uri('goods', $v['goods_id'], 'title');
            $sku_info = goods_helper::get_sku_property($v['id']);
            $list[$k]['sku_info'] = $goods_title . ' ' . $sku_info;
        }

        return $list;
    }

    public function gift_add() {
        $goods_id = Request::Post('goods_id', 0);
        $num = Request::Post('num', 0);
        $gift_sku_id = Request::Post('gift_sku_id', 0);

        if (!$goods_id) {
            return '请选择要添加赠品的商品';
        }

        if (!$gift_sku_id) {
            return '请选择要赠送商品';
        }

        if (!$num) {
            return '请填写要赠送的数量';
        }

        //         $gift_info = _uri('goods_gift_relation', array('goods_id'=>$goods_id, 'gift_sku_id'=>$gift_sku_id));

        $info = array(
            'goods_id' => $goods_id,
            'gift_sku_id' => $gift_sku_id,
            'gift_num' => $num,
            'gift_id' => _uri('sku', $gift_sku_id, 'goods_id'),
        );

        $id = _model('goods_gift_relation')->create($info);

        $info = _uri('goods_gift_relation', $id);

        $list = array();
        $goods_title = _uri('goods', $info['gift_id'], 'title');
        $sku_info = goods_helper::get_sku_property($info['gift_sku_id']);
        $list['sku_info'] = $goods_title . ' ' . $sku_info;
        $list['gift_num'] = $info['gift_num'];
        $list['id'] = $info['id'];

        return array('info' => 'ok', 'data' => $list);
    }

    /**
     * 添加商品
     */
    public function add() {
        $id = Request::getParam('id', 0);

        //        $category_id = Request::getParam('category_id', 0);
        //
        //        if (!$id) {
        //            if (!$category_id) {
        //                @$category_id = $_SESSION['goods_add_category_id'];
        //            } else {
        //                $_SESSION['goods_add_category_id'] = $category_id;
        //            }
        //        }

        // 获取商品信息
        if ($id) {
            $goods_info = _uri('goods', $id);
            if (!$goods_info) {
                return '该商品不存在或被删除';
            }
            //            if (!$category_id) {
            //                if ($goods_info['id']) {
            //                    $category_id = $goods_info['category_id'];
            //                }
            //            }
            $goods_info['price'] = goods_helper::get_price_by_id($id, 'max');
            $goods_info['stock'] = goods_helper::get_stock_by_id($id);
            $goods_info['diff_price'] = goods_helper::get_diff_price_by_goods_id($id);
            $goods_info['bbcoin'] = goods_helper::get_bbcoin_by_goods_id($id);
            $goods_info['diff_bbcoin'] = goods_helper::get_diff_bbcoin_by_goods_id($id);

            //            $sku_ids = _model('sku_relation')->getFields('sku_id', array('goods_id' => $id), ' ORDER BY `property_id` ASC , `property_value_id` ASC, `sku_id` ASC ');
            //            $sku_ids = array_unique($sku_ids);
            //
            //            $sku_list = array();
            //            if (!empty($sku_ids[0])) {
            //                foreach ($sku_ids as $k => $v) {
            //                    $sku_info = _uri('sku', array('id' => $v));
            //                    $line_list = goods_helper::get_property_value_by_sku_id($v);
            //
            //                    $sku_value_ids = '';
            //                    foreach ($line_list as $key => $value) {
            //                        foreach ($value['value_list'] as $k1 => $v1) {
            //                            $sku_value_ids .= '-' . $v1['property_value_id'];
            //                        }
            //                    }
            //
            //                    $sku_info['line_list'] = $line_list;
            //                    $sku_info['sku_value_ids'] = trim($sku_value_ids, '-');
            //                    $sku_list[] = $sku_info;
            //                }
            //            } else {
            //                $sku_info = _uri('sku', array('goods_id' => $id));
            //            }

            // 获取渠道列表
            $select_channel_list = channel_helper::get_goods_sku_channel_list($id);
            Response::assign('select_channel_list', $select_channel_list);

            Response::assign('id', $id);
            //Response::assign('sku_list', $sku_list);
            Response::assign('goods_info', $goods_info);
        }


        $channel_list = channel_helper::get_channel_list();
        Response::assign('channel_list', $channel_list);

        $category_list = goods_config::goods_category();
        Response::assign('category_list', $category_list);
        Response::display('admin/add.html');
    }

    /**
     * 保存
     */
    public function save() {
        $id = Request::getParam('id', 0);
        $info = Request::getParam('info', array());
        $sku = Request::getParam('sku', array());
        $cover = Request::getParam('cover', 0);
        $image = Request::getParam('image', array());
        $channel_ids = Request::getParam('channel_ids', array());
        $icon = '';
        $sku_cover = '';

        if (isset($_FILES['icon'])) {
            $icon = $_FILES['icon'];
        }
        if (isset($_FILES['sku_cover'])) {
            $sku_cover = $_FILES['sku_cover'];
        }

        foreach ($info as $k => $v) {
            if (is_array($v)) {
                foreach ($v as $key => $value) {
                    if (!is_numeric($value)) {
                        $v[$key] = trim(AnFilter::filter_string($value));
                    }
                }
            } elseif (!is_numeric($v)) {
                //过滤掉content里面的embed和object标签
                if ($k == 'content') {
                    $v = preg_replace('/<(embed|object) (.*?)>/i', '', $v);
                }
                $info[$k] = trim(AnFilter::filter_string($v));
            }
        }

        foreach ($sku as $k => $v) {
            if (is_array($v)) {
                foreach ($v as $key => $value) {
                    if (!is_numeric($value)) {
                        $v[$key] = trim(AnFilter::filter_string($value));
                    }
                }
            } elseif (!is_numeric($v)) {
                $info[$k] = trim(AnFilter::filter_string($v));
            }
        }

        if (!isset($info['title']) || !$info['title']) {
            return '请填写商品标题';
        }
        if (!isset($info['unit']) || !$info['unit']) {
            return '请填写商品单位';
        }
        if (!isset($info['cost']) || !$info['cost']) {
            return '请填写商品成本';
        }
        if (!isset($info['price']) || !$info['price']) {
            return '请填写商品价格';
        }
        if (!isset($info['stock']) || $info['stock'] == '') {
            return '请填写商品库存数量';
        }
        if (!isset($info['content']) || !$info['content']) {
            return '请填写商品介绍';
        }
        if (!isset($info['cube']) || !$info['cube']) {
            return '请填写商品体积';
        }
        if (!isset($info['weight']) || !$info['weight']) {
            return '请填写商品重量';
        }

        $tmp_sku['price'] = $info['price'];
        $tmp_sku['stock'] = $info['stock'];

        if (trim($info['bbcoin']) == '') {
            // TODO bbcoin 如果未设置抱抱币, 则设置为同出厂价, 忽略小数位, 向上取整
            $tmp_sku['bbcoin'] = ceil($info['price']);
        } else {
            // TODO bbcoin 如果设置了抱抱币, 直接忽略小数位
            $tmp_sku['bbcoin'] = intval($info['bbcoin']);
        }

        // 差价
        $tmp_sku['diff_price'] = $info['diff_price'];
        unset($info['diff_price']);

        // 差币
        $tmp_sku['diff_bbcoin'] = $info['diff_bbcoin'];
        unset($info['diff_bbcoin']);

        // 查询属性
        if (isset($sku['price'])) {
            foreach ($sku['property'] as $k => $v) {
                $property_value_ids[$v] = _model('property_value')->getFields('id', array('property_id' => $v));
            }
        }

        // 上传封面图片
        $info['cover'] = $cover;

        // sku 封面
        $sku_cover_input = $this->exchangeArr($sku_cover);

        $new_goods = 1;
        if ($id) {
            // 更新当前分类信息
            $new_goods = 0;
            _model('goods')->update($id, $info);
        } else {
            $id = _model('goods')->create($info);

            // 上传商品图片
            foreach ($image as $k => $v) {
                if (!$v) {
                    continue;
                }
                attachment_helper::add_attachment_relation('goods', $id, $v);
            }
            attachment_helper::add_attachment_relation('goods', $id, $cover);
        }

        // 检查筛选的属性
        $property_list = goods_helper::get_property_by_id($id);

        $old_property_count = count($property_list);
        $now_property_count = 0;
        if (isset($sku['property'])) {
            $now_property_count = count($sku['property']);
        }

        $is_same = 0;

        if ($old_property_count == $now_property_count && $now_property_count != 0) {
            foreach ($property_list as $k => $v) {
                if (in_array($v['id'], $sku['property'])) {
                    $is_same++;
                }
            }
        }

        if ($is_same == $old_property_count && $old_property_count != 0) {
            // 更新icon列表信息
            $icon_relation_list = _model('icon_relation')->getList(array('goods_id' => $id));
            $icon_keys = array_keys($icon['name']);
            $icon = $this->exchangeArr($icon);
            foreach ($icon_relation_list as $k => $v) {
                $icon_id = $v['property_value_id'];
                if (in_array($icon_id, $icon_keys)) {
                    if (!empty($icon[$icon_id]['name'])) {
                        // 删除原有图片
                        _model('icon_relation')->delete(array('goods_id' => $id, 'property_value_id' => $icon_id));
                        attachment_helper::del_attachment('icon', false, $v['attachment_id']);

                        // 更新现有图片
                        try {
                            $icon_upload_info = upload_file($icon[$icon_id], true, 'icon');
                        } catch (Exception $e) {
                            return $e->getMessage();
                        }

                        // 建立图片关系
                        $icon_info['attachment_id'] = $icon_upload_info['id'];
                        $icon_info['goods_id'] = $id;
                        $icon_info['property_value_id'] = $icon_id;
                        _model('icon_relation')->create($icon_info);
                        unset($icon[$icon_id]);
                    }
                } else {
                    _model('icon_relation')->delete(array('goods_id' => $id, 'property_value_id' => $icon_id));
                    attachment_helper::del_attachment('icon', false, $v['attachment_id']);
                }
            }

            // 更新新添加的icon
            if (count($icon)) {
                foreach ($icon as $k => $v) {
                    if (!empty($v['name'])) {
                        try {
                            $icon_info = upload_file($v, true, 'icon');
                        } catch (Exception $e) {
                            return $e->getMessage();
                        }
                        $icon_filter = array(
                            'goods_id' => $id,
                            'property_value_id' => $k
                        );
                        $icon_relation_info = array(
                            'goods_id' => $id,
                            'property_value_id' => $k,
                            'attachment_id' => $icon_info['id']
                        );
                        $icon_relation = _uri('icon_relation', $icon_filter);
                        if (empty($icon_relation['id'])) {
                            _model('icon_relation')->create($icon_relation_info);
                        } else {
                            _model('icon_relation')->update($icon_relation['id'], $icon_relation_info);
                        }
                    }
                }
            }

            // 更新sku信息
            $sku_ids = _model('sku')->getFields('id', array('goods_id' => $id));
            // 关联渠道表
            $this->save_channel_ids($id, $sku_ids[0], $channel_ids);
            $sku_input = $sku['price'];
            foreach ($sku_ids as $k => $sku_id) {
                $sku_relation_list = _model('sku_relation')->getList(array('sku_id' => $sku_id));
                $property_value_ids_count = count($sku_relation_list);
                $have_same_property = 0;
                foreach ($sku_input as $sku_k => $sku_v) {
                    $curr_property_value_ids = explode('-', $sku_k);
                    $value_same = 0;
                    foreach ($sku_relation_list as $value_k => $value_v) {
                        if (in_array($value_v['property_value_id'], $curr_property_value_ids)) {
                            $value_same++;
                        }
                    }
                    if ($value_same == $property_value_ids_count) {
                        $have_same_property = 1;
                        $curr_sku_ids = $sku_k;
                        unset($sku_input[$sku_k]);
                        break;
                    }
                }
                // 拥有相同属性就更新
                if ($have_same_property == 1) {
                    // 更新sku信息
                    $new_sku['goods_id'] = $id;
                    $new_sku['price'] = $sku['price'][$curr_sku_ids];
                    $new_sku['stock'] = $sku['stock'][$curr_sku_ids];
                    _model('sku')->update($sku_id, $new_sku);

                    // 上传sku图片
                    if (!empty($sku_cover_input[$curr_sku_ids]['name'])) {
                        // 删除原有图片
                        $attachment_relation_info = _uri('attachment_relation', array(
                            'res_name' => 'sku',
                            'res_id' => $sku_id
                        ));
                        if (!empty($attachment_relation_info)) {
                            attachment_helper::del_attachment('sku', $sku_id, $attachment_relation_info['attachment_id']);
                        }

                        // 更新现有图片
                        try {
                            $sku_cover_info = upload_file($sku_cover_input[$curr_sku_ids], true, 'sku');
                        } catch (Exception $e) {
                            return $e->getMessage();
                        }

                        // 建立图片关系
                        attachment_helper::add_attachment_relation('sku', $sku_id, $sku_cover_info['id']);
                    }

                    // 更新sku_ralation信息
                    $curr_property_value_ids = explode('-', $curr_sku_ids);
                    foreach ($curr_property_value_ids as $curr_property_value_id) {
                        $tmp_value = $sku['tmp_value'][$curr_property_value_id];
                        $property_filter = array(
                            'sku_id' => $sku_id,
                            'property_value_id' => $curr_property_value_id
                        );
                        _model('sku_relation')->update($property_filter, array('tmp_value' => $tmp_value));
                    }
                    unset($new_sku);
                } else {
                    // 未拥有相同属性 删除原有数据
                    // 删除原有图片
                    $attachment_relation_info = _uri('attachment_relation', array(
                        'res_name' => 'sku',
                        'res_id' => $sku_id
                    ));
                    if (!empty($attachment_relation_info)) {
                        attachment_helper::del_attachment('sku', $sku_id, $attachment_relation_info['attachment_id']);
                    }

                    // 删除sku信息
                    _model('sku')->delete($sku_id);
                    _model('sku_relation')->delete(array('sku_id' => $sku_id));
                }
            }

            // 插入新添加的sku属性
            if (count($sku_input)) {
                foreach ($sku_input as $input_sku_ids => $v) {
                    // 更新sku信息
                    $new_sku['goods_id'] = $id;
                    $new_sku['price'] = $sku['price'][$input_sku_ids];
                    $new_sku['stock'] = $sku['stock'][$input_sku_ids];
                    $sku_id = _model('sku')->create($new_sku);

                    // 上传sku图片
                    if (!empty($sku_cover_input[$input_sku_ids]['name'])) {
                        try {
                            $sku_cover_info = upload_file($sku_cover_input[$input_sku_ids], true, 'sku');
                        } catch (Exception $e) {
                            return $e->getMessage();
                        }

                        // 建立图片关系
                        attachment_helper::add_attachment_relation('sku', $sku_id, $sku_cover_info['id']);
                    }

                    // 插入sku_ralation信息
                    $curr_property_value_ids = explode('-', $input_sku_ids);
                    foreach ($curr_property_value_ids as $curr_property_value_id) {
                        foreach ($property_value_ids as $property_k => $property_v) {
                            if (in_array($curr_property_value_id, $property_v)) {
                                $property_id = $property_k;
                                break;
                            }
                        }
                        $sku_relation_info['goods_id'] = $id;
                        $sku_relation_info['sku_id'] = $sku_id;
                        $sku_relation_info['property_value_id'] = $curr_property_value_id;
                        $sku_relation_info['property_id'] = $property_id;
                        $sku_relation_info['tmp_value'] = $sku['tmp_value'][$curr_property_value_id];
                        _model('sku_relation')->create($sku_relation_info);
                    }
                    unset($new_sku);
                }
            }
        } else {

            // 删除原有所有sku属性
            $sku_ids = _model('sku')->getFields('id', array('goods_id' => $id));

            // 创建新属性
            $tmp_sku['goods_id'] = $id;

            if (isset($sku['price'])) {
                if (!empty($sku_ids)) {
                    $attachment_relation_list = _model('attachment_relation')->getList(array(
                        'res_name' => 'sku',
                        'res_id' => $sku_ids
                    ));

                    _model('sku')->delete(array('goods_id' => $id));

                    _model('sku_relation')->delete(array('goods_id' => $id));

                    _model('icon_relation')->delete(array('goods_id' => $id));
                }
                //上传icon图片
                $icon = $this->exchangeArr($icon);
                foreach ($icon as $k => $v) {
                    if (!empty($v['name'])) {
                        try {
                            $icon_info = upload_file($v, true, 'icon');
                        } catch (Exception $e) {
                            return $e->getMessage();
                        }

                        $icon_filter = array(
                            'goods_id' => $id,
                            'property_value_id' => $k
                        );
                        $icon_relation_info = array(
                            'goods_id' => $id,
                            'property_value_id' => $k,
                            'attachment_id' => $icon_info['id']
                        );
                        $icon_relation = _uri('icon_relation', $icon_filter);
                        if (empty($icon_relation['id'])) {
                            _model('icon_relation')->create($icon_relation_info);
                        } else {
                            _model('icon_relation')->update($icon_relation['id'], $icon_relation_info);
                        }
                    }
                }

                //上传sku图片
                $sku_cover = $this->exchangeArr($sku_cover);
                foreach ($sku_cover as $k => $v) {
                    if (!empty($v['name'])) {
                        try {
                            $sku_cover_info[$k] = upload_file($v, true, 'sku');
                        } catch (Exception $e) {
                            return $e->getMessage();
                        }
                    }
                }

                // 拼接sku_info
                $new_sku['price'] = $sku['price'];
                $new_sku['stock'] = $sku['stock'];
                $new_sku = $this->exchangeArr($new_sku);

                // 创建sku记录
                foreach ($new_sku as $k => $v) {
                    $v['goods_id'] = $id;
                    $sku_id = _model('sku')->create($v);

                    // 建立图片关系
                    attachment_helper::add_attachment_relation('sku', $sku_id, $sku_cover_info[$k]['id']);

                    // 添加对应的sku_relation记录
                    $value_ids = explode('-', $k);
                    foreach ($value_ids as $key => $value) {
                        // 获取属性id
                        foreach ($property_value_ids as $value_k => $value_v) {
                            if (in_array($value, $value_v)) {
                                $property_id = $value_k;
                                break;
                            }
                        }
                        $sku_relation_info['goods_id'] = $id;
                        $sku_relation_info['sku_id'] = $sku_id;
                        $sku_relation_info['property_value_id'] = $value;
                        $sku_relation_info['property_id'] = $property_id;
                        $sku_relation_info['tmp_value'] = $sku['tmp_value'][$value];
                        _model('sku_relation')->create($sku_relation_info);
                    }
                }
            } else {
                // 添加一条临时 sku
                if ($new_goods) {
                    $sku_id = _model('sku')->create($tmp_sku);
                    // 关联渠道
                    $this->save_channel_ids($id, $sku_id, $channel_ids);
                } else {
                    _model('sku')->update(array('goods_id' => $id), $tmp_sku);
                    $this->save_channel_ids($id, $sku_ids[0], $channel_ids);
                }
            }
        }

        return array('保存成功', 'success', AnUrl('goods/admin'));
    }

    /**
     * 关联渠道商品
     * @param unknown_type $goods_id
     * @param unknown_type $sku_id
     * @param unknown_type $channel_ids
     */
    private function save_channel_ids($goods_id, $sku_id, $channel_ids) {
        if ($channel_ids) {

            $filter['goods_id'] = $goods_id;
            $filter['sku_id'] = $sku_id;
            $channel_info = _model('channel_goods_sku_relation')->read($filter);
            if ($channel_info) {
                _model('channel_goods_sku_relation')->delete($filter);
            }

            $data['goods_id'] = $goods_id;
            $data['sku_id'] = $sku_id;
            $data['add_time'] = date('Y-m-d H:i:s');

            foreach ($channel_ids as $k => $v) {
                $data['channel_id'] = $v;
                _model('channel_goods_sku_relation')->create($data);
            }
        }
    }

    /**
     * 删除
     * @return array
     */
    public function delete() {
        $id = Request::getParam('id');

        if (!$id) {
            return '请选择要删除的内容';
        }

        $ids = explode(',', trim($id, ','));
        foreach ($ids as $k => $v) {
            if (!$v) {
                continue;
            }

            $goods_info = _uri('goods', (int)$v);
            if (!$goods_info) {
                continue;
            }

            if ($goods_info['is_sale']) {
                return '不能删除已上架的商品';
            }

            if (1 == $goods_info['status']) {
                _model('goods')->update($v, array('status' => 0));
            } else {
                _model('goods')->delete($v);
            }
        }

        return 'ok';
    }

    /**
     * 更改状态
     * @return array
     */
    public function change_status() {
        $id = Request::getParam('id', 0);
        $status = Request::getParam('status', 1);

        if (!$id) {
            return '请选择要更改的内容';
        }

        $goods_info = _uri('goods', $id);
        if ($status == $goods_info['status']) {
            return '已经执行过此操作，不用重复提交';
        }

        if (1 == $status) {
            _model('goods')->update($id, array('status' => 1));
        }

        return 'ok';
    }

    /**
     * 是否盘点
     * @return array
     */
    public function change_init() {
        $id = Request::getParam('id');

        if (!$id) {
            return '请选择要删除的内容';
        }

        $ids = explode(',', trim($id, ','));
        foreach ($ids as $k => $v) {
            if (!$v) {
                continue;
            }

            $goods_info = _uri('goods', (int)$v);
            if (!$goods_info) {
                continue;
            }

            $is_sale = $goods_info['is_init'] ? 0 : 1;

            _model('goods')->update($v, array('is_init' => $is_sale));
        }

        return 'ok';
    }

    /**
     * 是否上架
     * @return array
     */
    public function change_sale() {
        $id = Request::getParam('id');

        if (!$id) {
            return '请选择要删除的内容';
        }

        $ids = explode(',', trim($id, ','));
        foreach ($ids as $k => $v) {
            if (!$v) {
                continue;
            }

            $goods_info = _uri('goods', (int)$v);
            if (!$goods_info) {
                continue;
            }

            $is_sale = $goods_info['is_sale'] ? 0 : 1;

            _model('goods')->update($v, array('is_sale' => $is_sale));
        }

        return 'ok';
    }

    /**
     * ajax删除图片
     * @return array
     */
    public function set_cover() {
        $goods_id = Request::getParam('goods_id', 0);
        $file_id = Request::getParam('file_id', 0);

        if (!$goods_id) {
            return '请选择要设置位封面的图片';
        }

        _model('goods')->update($goods_id, array('cover' => $file_id));

        return 'ok';
    }

    /**
     * ajax删除图片
     * @return array
     */
    public function delete_res() {
        $res_name = Request::getParam('res_name', 'recommend');
        $res_id = Request::getParam('res_id', 0);
        $file_id = Request::getParam('file_id', 0);
        $is_cover = Request::getParam('is_cover', 0);
        $cover = Request::getParam('cover', 0);

        if (!$file_id) {
            return '请选择需要删除的图片';
        }

        attachment_helper::del_attachment_relation($res_name, $res_id, $file_id);

        if ($cover && $res_id) {
            _model('goods')->update($res_id, array('cover' => $cover));
        } else {
            if ($is_cover == 1) {
                _model('goods')->update($res_id, array('cover' => ''));
            }
        }

        return 'ok';
    }

    /**
     * ajax查看推荐信息
     * @return array
     */
    public function view_recommend() {
        $goods_id = Request::getParam('goods_id', 0);

        if (!$goods_id) {
            return '请选择要推荐的内容';
        }

        $goods_info = _uri('goods', $goods_id);

        $recommend_relation_list = _model('attachment_relation')->getList(array(
            'res_id' => $goods_id,
            'res_name' => 'recommend'
        ), ' LIMIT 0,1');
        PRINT_R($recommend_relation_list);
        if (!empty($recommend_relation_list[0]['attachment_id'])) {
            $file_info = _uri('attachment', $recommend_relation_list[0]['attachment_id']);

            $view_info['recommend'] = $goods_info['recommend'];
            $view_info['attachment_path'] = $file_info['path'];
            $view_info['attachment_id'] = $file_info['id'];

            return array('info' => 'ok', 'data' => $view_info);
        }

        return '暂无图片';
    }

    /**
     * ajax推荐到首页
     * @return array
     */
    public function check_recommend() {
        $goods_id = Request::getParam('goods_id', 0);
        $recommend = Request::getParam('recommend', 0);
        $file_id = Request::getParam('file_id', 0);
        if (!$goods_id) {
            return '请选择要推荐的内容';
        }

        $goods_info = _uri('goods', $goods_id);

        _model('goods')->update($goods_id, array('recommend' => $recommend));

        return 'ok';
    }

    /**
     * ajax 获取关联商品信息
     */
    public function get_goods_list() {
        $pid = Request::Post('pid', 0);
        $goods_id = Request::getParam('goods_id', 0);

        if ($pid < 0) {
            return array('info' => 'ok', 'data' => '');
        }

        $list = array();
        $list = _model('category')->getList(array('parent_id' => $pid, 'res_name' => 'goods', 'status' => 1));

        if ($list) {
            $method = 'category';
        } else {
            $method = 'goods';
            $filter = array('category_id' => $pid, 'status' => 1);
            $count = _model('goods')->getTotal($filter);
            if (!$count) {
                return array('info' => 'ok', 'data' => '<div style="padding:10px;">该分类下没有商品</div>');
            }

            $relation_ids = goods_helper::get_goods_relation_ids($goods_id);
            $list = _model('goods')->getList($filter);
            foreach ($list as $k => $v) {
                if ($v['id'] == $goods_id || in_array($v['id'], $relation_ids)) {
                    unset($list[$k]);
                }
            }
        }
        Response::assign('method', $method);
        Response::assign('list', $list);
        $data = Response::fetch(MODULE_PATH . '/goods/template/admin/slt_goods.html');

        return array('info' => 'ok', 'data' => $data);
    }

    /**
     * 建立促销商品关联
     * @return string
     */
    public function add_relation_goods() {
        $goods_id = Request::getParam('goods_id', 0);
        $relation_ids = explode(',', AnFilter::filter_string(Request::getParam('relation_ids', '')));
        $discount_arr = explode(',', AnFilter::filter_string(Request::getParam('discount_arr', '')));
        $price_arr = explode(',', AnFilter::filter_string(Request::getParam('price_arr', '')));
        $relation_flip = array_flip($relation_ids);
        if (!$goods_id) {
            return '请选择需要进行关联的主商品';
        }

        // 更新原有数据
        $delete_ids = array();
        $goods_relation_ids = goods_helper::get_goods_relation_ids($goods_id);
        if ($goods_relation_ids) {
            foreach ($goods_relation_ids as $k => $v) {
                $filter = array(
                    'goods_id' => $goods_id,
                    'relation_goods_id' => $v
                );
                if (in_array($v, $relation_ids)) {
                    $delete_ids[] = $v;
                    $key = $relation_flip[$v];
                    $info = array(
                        'discount' => (int)$discount_arr[$key],
                        'sale_price' => $price_arr[$key]
                    );
                    _model('goods_relation')->update($filter, $info);
                } else {
                    //_model('goods_relation')->delete($filter);
                }
            }
        }

        if ($relation_ids) {
            foreach ($relation_ids as $k => $v) {
                if (!in_array($v, $delete_ids) && $v) {
                    $key = $relation_flip[$v];
                    $info = array(
                        'goods_id' => $goods_id,
                        'relation_goods_id' => $v,
                        'discount' => (int)$discount_arr[$key],
                        'sale_price' => $price_arr[$key]
                    );
                    _model('goods_relation')->create($info);
                }
            }
        }

        return 'ok';
    }

    /**
     * ajax 获取已添加关联商品信息
     */
    public function get_relation_list() {
        $goods_id = Request::getParam('goods_id', 0);
        if (!$goods_id) {
            return '当前商品还有没关联商品';
        }

        $relation_list = goods_helper::get_goods_relation_list($goods_id);

        Response::assign('relation_list', $relation_list);
        $data = Response::fetch(MODULE_PATH . '/goods/template/admin/relation_list.html');

        return array('info' => 'ok', 'data' => $data);
    }

    public function eidt_realtion_goods() {
        $id = Request::getParam('id', 0);
        $discount = Request::getParam('discount', '');
        $sale_price = Request::getParam('sale_price', '');
        if (!$id) {
            return '请选择需要修改的商品';
        }

        $info = array(
            'discount' => $discount,
            'sale_price' => $sale_price
        );

        _model('goods_relation')->update(array('id' => $id), $info);

        return 'ok';
    }

    public function delete_relation_goods() {
        $id = Request::getParam('id', 0);
        if (!$id) {
            return '请选择要删除的商品';
        }

        _model('goods_relation')->delete(array('id' => $id));

        return 'ok';
    }

    /**
     * 三维数组转换
     * @return array
     */
    private function exchangeArr($arr) {
        if (!is_array($arr)) {
            return;
        }
        foreach ($arr as $key => $value) {
            foreach ($value as $k => $v) {
                $new_arr[$k][$key] = $v;
            }
        }
        return $new_arr;
    }
}

?>
